import { Command } from '../constant';
import { Dispatch } from 'typings';
import { getActionProxy } from '@/redux/action-util';
import * as reduxStore from '@/redux/store';
import Action from './action';
import packageRzIndexMain from '../reducers/main';
import Taro from '@tarojs/taro';
import api from 'api';

export default (dispatch?: Dispatch) => {
  const actions = {
    action: getActionProxy<typeof Action>(Action)(dispatch),

    /**
     * 初始化数据
     */
    async init() {
      await actions.loadReducer();

      if (!Taro.getStorageSync('aesKey')) {
        await actions.action.getAPPSecret();
      } else {
        //获取社区名称
        await actions.action.getSelectDistance();
      }

      // 查询腾讯企业微信客服(快递需求)
      // if (!Taro.getStorageSync('serviceonline')) {
      //   let res = await api.pagesIndexController.getServiceonline();
      //   if (res.code == '200') {
      //     Taro.setStorageSync('serviceonline', res.data)
      //   }
      // }
    },
    /**
     * 重置
     */
    async clean() {
      //@ts-ignore
      __TARO_ENV !== 'h5' && (await actions.unloadReducer());
      dispatch({ type: Command.clean });
    },

    /**
     * 动态添加注入reducer
     */
    async loadReducer() {
      reduxStore.registerReducer({
        packageRzIndexMain,
      });
    },

    /**
     * 卸载reducer
     */
    async unloadReducer() {
      if (reduxStore.deregister) {
        reduxStore.deregister(['packageRzIndexMain']);
      } else {
        console.error('请在redux/store中实现deregister逻辑. ');
      }
    },
  };

  return { actions };
};

//create by moon https://github.com/creasy2010/moon
